package com.jeesite.modules.dp.web;

import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.jeesite.modules.dp.entity.order.DpOrder;
import com.jeesite.modules.dp.service.order.DpOrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.binarywang.wxpay.bean.notify.WxPayNotifyResponse;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.jeesite.modules.wxpay.WxPayConfiguration;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Controller
@Api(tags = "wxpay - 微信支付相关")
@RequestMapping(value = "wx")
@ConditionalOnProperty(name = {"user.enabled", "web.core.enabled"}, havingValue = "true", matchIfMissing = true)

public class WxPayResultController {

    private WxPayService wxPayService;

    @Autowired
    private DpOrderService dpOrderService;

    private final Logger log = LoggerFactory.getLogger(WxPayResultController.class);

    @ApiOperation(value = "扫码支付回调通知处理")
    @PostMapping("/notify/scanpay")
    @ResponseBody
    public String parseScanPayNotifyResult(@RequestBody String xmlData) throws WxPayException {
        log.info("收到微信支付通知，content: {}", xmlData);
        if (wxPayService == null) {
            wxPayService = WxPayConfiguration.wxService();
        }
        final WxPayOrderNotifyResult result = wxPayService.parseOrderNotifyResult(xmlData);
        log.info("微信支付通知解析结果， outpayno:{}, returnCode: {}, resultCode: {}, returnMsg: {}, errMsg: {}"
                , result.getOutTradeNo(), result.getReturnCode(), result.getResultCode()
                , result.getReturnMsg(), result.getErrorMessage());
        // 处理业务逻辑
        DpOrder dpOrder = dpOrderService.findByOutpayno(result.getOutTradeNo());
        if (dpOrder != null) {
            dpOrderService.doOrderPaySuccess(dpOrder.getId());
        }
        return WxPayNotifyResponse.success("成功");
    }


}
